import React, { PureComponent,Fragment } from "react";
import { connect } from "dva";
import router from 'umi/router';
import { Row, Col, Card, Icon, Button, message, Divider, Form, Input, Popconfirm, Badge, Select} from "antd";
import StandardTable from '../../../components/StandardTable';
import Authorized from '../../../utils/Authorized';
import styles from '../../Pbulic.less';


const FormItem = Form.Item;
const { Option } = Select;

const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

@connect(({ user,loading }) => ({
  resdata: user.resdata,
  loading: user.loading,
  // loading: loading.models.equipment_integrated,
}))
@Form.create()
export default class ListTable extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      currentPage: 1,
      pageSize: 10,
      selectedRows: [],
      formValues: {},
    };
  }

  componentWillUnmount() {

  }


  componentDidMount() {
    const { pageSize } = this.state;
    const { location, dispatch} = this.props;
    const pagesquery = location.query;

    // 列表
    this.getDataList(pagesquery,pageSize,1);


  }


  // componentWillReceiveProps(nextProps) {
  //   // 外层发起刷新数据请求
  //   if (nextProps.isReloadList === true && this.props.isReloadList === false) {
  //     const { pageSize } = this.state;
  //     this.getDataList({},pageSize,1);
  //     this.props.sotpReloadList();
  //   }
  // }


  getDataList(params,pageSize,currentPage) {
    const { dispatch, match } = this.props;
    dispatch({
      type: 'user/fetch_user_list',
      payload: {
        pageSize,
        currentPage,
        // ...pagesquery,
        ...params,
      },
    });
  }

  // 批量删除
  handleListDel = (id) => {
    const { dispatch } = this.props;
    const { selectedRows,formValues, pageSize, currentPage } = this.state;
    if(!id && !selectedRows) return;
    const userIds= id ? [id] : selectedRows;

    dispatch({
      type: 'user/action_user_del',
      payload: {
        userIds,
      },
    }).then(()=>{
      this.setState({
        selectedRows: [],
      });
    }).then(()=>{
      message.success("所选用户已删除")
    }).then(()=>{
      this.getDataList(formValues,pageSize,currentPage);
    });


  };


  // 分页、排序、筛选变化时触发
  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues,pageSize } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      // currentPage: pagination.current,
      // pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };

    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    this.setState({
      currentPage:pagination.current
    },()=>{
      this.getDataList(params,pageSize,pagination.current);
    })

  };

  // 重置表单
  handleFormReset = () => {
    const { form } = this.props;
    const {pageSize,currentPage} = this.state;
    //form.resetFields();
    form.setFieldsValue({
      username:undefined,
      userType:undefined,
    });
    this.setState({
      formValues: {},
    });
    this.getDataList({},pageSize,1);
  };


  // 表格复选框选中
  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows.map(item => item.userId),
    });
  };

  // 表单搜索
  handleSearchSubmit = e => {
    e.preventDefault();

    const { form } = this.props;
    const { pageSize } = this.state;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      this.setState({
        formValues: fieldsValue,
      });

      this.getDataList(fieldsValue,pageSize,1);
    });
  };



  // 链接跳转-------------------
  handleLink = (action,detailInfoId) =>{
    const { dispatch, match } = this.props;
    const { formValues, currentPage} = this.state;
    let linkpath;
    switch (action) {
      case 'add':
        linkpath = `/system/users/detail/add`;
        break;
      case 'edit':
        linkpath = `/system/users/${detailInfoId}/edit`;
        break;
      case 'info':
        linkpath = `/system/users/${detailInfoId}/info`;
        break;
      default:
        break;
    }
    router.push({ pathname:`${linkpath}`,  query: { ...formValues, currentPage} });
  }


  // 搜索内容
  renderSearchForm() {
    const { form,  location } = this.props;
    const { getFieldDecorator } = form;
    const pagesquery = location.query;
    return (
      <Form onSubmit={this.handleSearchSubmit} >
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem
              label="用户类型"
            >
              {getFieldDecorator('userType', {
                initialValue: pagesquery && pagesquery.userType ? pagesquery.userType : undefined,
              })(
                <Select
                  placeholder="请选择用户类型"
                  allowClear={true}
                >
                  <Option key={"01"} value={"01"}>甲方单位</Option>
                  <Option key={"02"} value={"02"}>维保单位</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="用户名称">
              {getFieldDecorator('username',{
                initialValue: pagesquery && pagesquery.username ? pagesquery.username : undefined,
              })(<Input placeholder="用户名称" />)}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <div style={{ float: 'right', marginBottom: 24 }}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </div>
          </Col>

        </Row>
      </Form>
    );
  }


  render() {

    const { resdata, loading, match } = this.props;
    const { selectedRows } = this.state;

    const columns = [
      {
        title: "用户名",
        dataIndex: "username",
      },
      {
        title: "真实姓名",
        dataIndex: "realName",
      },
      {
        title: "电话",
        dataIndex: "mobile",
      },
      {
        title: "角色",
        dataIndex: "roleName",
      },
      {
        title: "用户类型",
        dataIndex: "userType",
        render: text => (text=="01" ? '甲方单位' : '维保单位')
      },
      // {
      //   title: "创建时间",
      //   dataIndex: "createTime",
      //   render: text => (text ? moment(text).format("YYYY-MM-DD HH:mm") : "--")
      // },
      {
        title: "状态",
        dataIndex: "status",
        render: text =>
          text == "1" ? (
            <Badge status="success" text="正常" />
          ) : text == "0" ? (
            <Badge status="processing" text="禁用" />
          ) : (
            <Badge status="default" text="无效" />
          )
      },
      {
        title: "操作",
        dataIndex: "Action",
        width: "15%",
        render: (text, row) => (
            <span>
              <Authorized authority={'10363'} >
                <a onClick={() => this.handleLink('edit',row.userId)}>修改</a>
                <Divider type="vertical" />
              </Authorized>
              <Authorized authority={'10364'} >
                <Popconfirm title="是否确定要删除?" onConfirm={() => this.handleListDel(row.userId)}  okText="是" cancelText="否">
                  <a >删除</a>
                </Popconfirm>
              </Authorized>
            </span>
        )
      }
    ];


    return (
      <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderSearchForm()}</div>

            <div className={styles.tableListOperator}>
              <Authorized authority={'10362'} >
                <Button icon="plus" type="primary"  onClick={() => this.handleLink('add',null)}>
                  新增用户
                </Button>
              </Authorized>
              <Authorized authority={'10365'} >
                <Popconfirm title="是否确定要批量删除?" onConfirm={() => this.handleListDel()}  okText="是" cancelText="否">
                  <Button icon="minus" type="default" disabled={selectedRows.length > 0 ? false : true}>
                    批量删除
                  </Button>
                </Popconfirm>
              </Authorized>

            </div>

            <StandardTable
              selectedRows={selectedRows}
              rowKey="userId"
              // scroll={{ x: 1500 }}
              loading={loading.reslist}
              data={resdata}
              columns={columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />

          </div>
      </Card>

    );
  }
}
